import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import config from './config'

export interface ReponseData {
  code: number
  data?: any
  message: string
}

// axios实例
let service: AxiosInstance | any

service = axios.create({
  timeout: 5000
})

// 请求进度条配置
NProgress.configure({
  showSpinner: false
})

//配置开发和生产环境baseURL
axios.defaults.baseURL = import.meta.env.MODE === 'development' ? '/api' : config.BASI_API

// 请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    NProgress.start()
    //   先判断token
    // getToken() 请求头塞token
    return config
  },
  (error: any) => {
    console.error('error:', error)
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.reponse.use(
  (res: AxiosResponse) => {
    NProgress.done()
    if (res.status == 200) {
      const data: ReponseData = res.data
      if (data.code === 1) {
        return data
      } else {
        //   移出token
        // resetToken()
        ElMessage({
          message: data.message,
          type: 'error',
          duration: 2000
        })
      }
    } else {
      ElMessage({
        message: '网络错误',
        type: 'error',
        duration: 2000
      })
      return Promise.reject(new Error(res.data.message || 'Error'))
    }
  },
  (error: any) => {
    NProgress.done()
    console.error('error:', error)
    Promise.reject(error)
  }
)

export default service
